using System;
using System.Collections.Generic;
using GraphEditor.Runtime;
using UnityEngine;

namespace GraphEditor.Sample.StateMachine.Runtime
{
    [Serializable]
    public class StateMachine : IElement
    {
        /// <summary>
        /// 状态集合
        /// </summary>
        [SerializeReference]
        public List<State> states;
        /// <summary>
        /// 起始状态
        /// </summary>
        [SerializeReference]
        public State startState;

        /// <summary>
        /// 当前状态
        /// </summary>
        private State _currentState;
        private Dictionary<Type, State> _states = new Dictionary<Type, State>();

        public string Id { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            foreach (State state in states)
            {
                _states[state.GetType()] = state;
            }
            if (startState != null)
            {
                ChangeState(startState.GetType());
            }
        }

        /// <summary>
        /// 更新当前状态
        /// </summary>
        public void Update()
        {
            _currentState?.Update(this);
        }

        public void ChangeState(Type stateType)
        {
            _currentState?.Exit(this);
            var newStateType = stateType;
            if (_states.ContainsKey(newStateType))
            {
                _currentState = _states[newStateType];
                _currentState.Enter(this);
            }
            else
            {
                Debug.LogError($"错误：状态 {newStateType.Name} 未在状态机中注册。");
            }
        }

        public void ChangeState<TState>() where TState : State
        {
            ChangeState(typeof(TState));
        }
    }
}